<template>
  <div class="course-container">
    <div class="header">
      <h2>全部课程</h2>
      <el-input
        v-model="searchQuery"
        placeholder="搜索课程..."
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch" />
        </template>
      </el-input>
    </div>

    <div v-loading="loading" class="course-list">
      <template v-if="!loading">
        <el-empty v-if="filteredCourses.length === 0" description="暂无课程数据" />
        
        <el-row v-else :gutter="20">
          <el-col
            v-for="course in paginatedCourses"
            :key="course.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card 
              class="course-card" 
              shadow="hover"
              @click="handleCourseClick(course)"
            >
              <div class="card-image-container">
                <img
                  class="course-image"
                  :src="course.couPic || defaultCourseImage"
                  :alt="course.couName"
                />
                <div v-if="course.couPrice > 0" class="price-tag">
                  ¥{{ course.couPrice }}
                </div>
              </div>
              
              <div class="card-content">
                <h3 class="course-title">{{ course.couName }}</h3>
                <p class="course-desc">{{ course.couIntroduction || '暂无课程描述' }}</p>
                <div class="course-stats">
                  <span><i class="el-icon-user"></i> {{ course.couCollNum || 0 }}</span>
                  <span><i class="el-icon-view"></i> {{ course.clicks || 0 }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页控件 -->
        <div class="pagination-container" v-if="filteredCourses.length > 0">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="filteredCourses.length"
            layout="prev, pager, next, jumper"
            background
            @current-change="handlePageChange"
          />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

// 路由和状态管理
const router = useRouter()
const authStore = useAuthStore()

// 数据状态
const loading = ref(true)
const courses = ref([])
const searchQuery = ref('')
const defaultCourseImage = ref(require('@/assets/fault.png'))

// 分页相关
const currentPage = ref(1)
const pageSize = ref(8) // 每页12个卡片

// 计算属性：分页后的课程数据
const paginatedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCourses.value.slice(start, end)
})

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 课程点击处理
const handleCourseClick = async (course) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在验证权限...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    // 确保用户信息已加载
    if (!authStore.userInfo) {
      await authStore.fetchUserInfo();
    }
    
    if (authStore.userInfo?.role === 0) {
      router.push({
        name: 'TeacherCourseDetailAll',
        params: { id: course.id }
      });
    } else if (authStore.userInfo?.role === 1) {
      router.push({
        name: 'CoursePurchase',
        params: { id: course.id }
      });
    } else {
      // 未登录用户处理
      try {
        await ElMessageBox.confirm('购买课程需要登录，是否立即登录？', '登录提示', {
          confirmButtonText: '去登录',
          cancelButtonText: '取消',
          type: 'warning'
        });
        router.push({
          path: '/login',
          query: { redirect: `/course-purchase/${course.id}` }
        });
      } catch (cancel) {
        // 用户点击取消不做任何操作
      }
    }
  } catch (error) {
    console.error('课程跳转失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  } finally {
    loading.close();
  }
}

// 获取课程数据
const fetchCourses = async () => {
  try {
    loading.value = true
    const response = await axios.get('/vod/course/listAll')
    
    // 兼容多种响应结构
    let courseData = []
    if (Array.isArray(response)) {
      courseData = response
    } else if (Array.isArray(response.data)) {
      courseData = response.data
    } else if (Array.isArray(response.data?.data)) {
      courseData = response.data.data
    } else {
      console.warn('未知响应结构:', response)
      throw new Error('无法解析的响应格式')
    }
    
    courses.value = courseData
  } catch (error) {
    console.error('请求失败详情:', error)
    ElMessage.error(`数据加载失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 搜索功能
const filteredCourses = computed(() => {
  if (!searchQuery.value) return courses.value
  
  const query = searchQuery.value.toLowerCase()
  return courses.value.filter(c => {
    const name = c.couName?.toLowerCase() || ''
    const intro = c.couIntroduction?.toLowerCase() || ''
    return name.includes(query) || intro.includes(query)
  })
})

const handleSearch = () => {
  currentPage.value = 1
}

// 生命周期钩子
onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.course-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 60px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.course-list {
  min-height: 500px;
  position: relative;
}

.course-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.card-image-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 56.25%;
  overflow: hidden;
  background-color: #f5f7fa;
}

.course-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.course-card:hover .course-image {
  transform: scale(1.05);
}

.price-tag {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 1;
}

.card-content {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.course-title {
  margin: 0 0 10px;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.course-desc {
  color: #666;
  font-size: 14px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 10px;
}

.course-stats {
  display: flex;
  justify-content: space-between;
  color: #888;
  font-size: 12px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.course-stats i {
  margin-right: 5px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .el-input {
    width: 100% !important;
  }
  
  .card-image-container {
    padding-top: 75%;
  }
  
  .pagination-container {
    margin-top: 20px;
  }
  
  .el-pagination button, 
  .el-pagination li:not(.number) {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    margin: 0 2px;
  }
}
</style>